<template>
  <div class="timestamp-tool">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>时间戳转换工具</h3>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <div class="inner-card-header">
                <div class="title">时间戳转日期时间</div>
              </div>
            </template>
            
            <el-form>
              <el-form-item>
                <el-input
                  v-model="timestampInput"
                  placeholder="请输入时间戳（毫秒或秒）"
                  @input="convertTimestampToDate"
                >
                  <template #append>
                    <el-select v-model="timestampUnit" style="width: 90px" @change="convertTimestampToDate">
                      <el-option label="毫秒" value="ms" />
                      <el-option label="秒" value="s" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <div class="result-wrapper">
                  <div v-if="dateResult" class="result-item">
                    <div class="label">日期时间：</div>
                    <div class="value">{{ dateResult }}</div>
                  </div>
                  <div v-if="dateResult" class="result-item">
                    <div class="label">ISO格式：</div>
                    <div class="value">{{ isoResult }}</div>
                  </div>
                  <div v-if="dateResult" class="result-item">
                    <div class="label">UTC时间：</div>
                    <div class="value">{{ utcResult }}</div>
                  </div>
                  <el-empty v-else description="请输入有效的时间戳" />
                </div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <div class="inner-card-header">
                <div class="title">日期时间转时间戳</div>
              </div>
            </template>
            
            <el-form>
              <el-form-item>
                <el-date-picker
                  v-model="dateInput"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="x"
                  @change="convertDateToTimestamp"
                />
              </el-form-item>

              <el-form-item>
                <div class="result-wrapper">
                  <div v-if="timestampResult" class="result-item">
                    <div class="label">Unix时间戳（秒）：</div>
                    <div class="value">{{ Math.floor(timestampResult / 1000) }}</div>
                  </div>
                  <div v-if="timestampResult" class="result-item">
                    <div class="label">Unix时间戳（毫秒）：</div>
                    <div class="value">{{ timestampResult }}</div>
                  </div>
                  <el-empty v-else description="请选择日期时间" />
                </div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <el-divider>当前时间</el-divider>

      <el-row>
        <el-col :span="24">
          <div class="current-time">
            <div class="time-display">{{ currentTime }}</div>
            <div class="timestamp-display">
              Unix时间戳（秒）：{{ Math.floor(Date.now() / 1000) }}
              <el-divider direction="vertical" />
              Unix时间戳（毫秒）：{{ Date.now() }}
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

const timestampInput = ref('')
const timestampUnit = ref('ms')
const dateResult = ref('')
const isoResult = ref('')
const utcResult = ref('')

const dateInput = ref('')
const timestampResult = ref('')

const currentTime = ref('')
let timer = null

// 格式化日期
const formatDate = (date) => {
  const pad = (num) => String(num).padStart(2, '0')
  
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
         `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

// 时间戳转日期
const convertTimestampToDate = () => {
  if (!timestampInput.value) {
    dateResult.value = ''
    isoResult.value = ''
    utcResult.value = ''
    return
  }

  try {
    let timestamp = parseInt(timestampInput.value)
    if (timestampUnit.value === 's') {
      timestamp *= 1000
    }

    const date = new Date(timestamp)
    if (isNaN(date.getTime())) {
      throw new Error('无效的时间戳')
    }

    dateResult.value = formatDate(date)
    isoResult.value = date.toISOString()
    utcResult.value = date.toUTCString()
  } catch (e) {
    ElMessage.error('请输入有效的时间戳')
    dateResult.value = ''
    isoResult.value = ''
    utcResult.value = ''
  }
}

// 日期转时间戳
const convertDateToTimestamp = () => {
  if (!dateInput.value) {
    timestampResult.value = ''
    return
  }
  timestampResult.value = parseInt(dateInput.value)
}

// 更新当前时间显示
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = formatDate(now)
}

// 组件挂载时启动定时器
onMounted(() => {
  updateCurrentTime()
  timer = setInterval(updateCurrentTime, 1000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.timestamp-tool {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.inner-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

h3 {
  margin: 0;
}

.box-card {
  margin-bottom: 20px;
}

.result-wrapper {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
}

.result-item {
  margin-bottom: 10px;
}

.result-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #606266;
  margin-bottom: 5px;
}

.value {
  color: #303133;
  font-family: monospace;
  word-break: break-all;
}

.current-time {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.time-display {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
  font-family: monospace;
}

.timestamp-display {
  color: #606266;
  font-family: monospace;
}
</style> 